package Thread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket serverSocket;
    private ExecutorService threadPool;
    private List<PrintWriter> allOut;

    public Server(){
        try{
            System.out.println("正在启动服务端...");
            serverSocket =new ServerSocket(8080);
            threadPool = Executors.newFixedThreadPool(30);
            allOut=new ArrayList<>();
            System.out.println("服务端启动完毕...");
        }catch(IOException e){
            e.printStackTrace();
        }
    }


    public void start(){
        try {
            System.out.println("正在等待客户链接...");
            Socket socket=serverSocket.accept();
            System.out.println("一个客户链接了!");
            ClientHandler handler=new ClientHandler(socket);
            threadPool.execute(handler);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private synchronized void broadcast(String message){
        for (PrintWriter out : allOut) {
            out.println(message);
        }

    }
    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;

        public ClientHandler(Socket socket){
            this.socket=socket;
            host=socket.getInetAddress().getHostAddress();
        }
        public void run(){
            PrintWriter pw=null;
            try{
                OutputStream out=socket.getOutputStream();
                pw=new PrintWriter(out,true);

                synchronized (Server.this){
                    allOut.add(pw);
                }
                broadcast(host+"加入了聊天室！");

                InputStream in=socket.getInputStream();
                Scanner scanner=new Scanner(in, StandardCharsets.UTF_8);
                String message;
                while(scanner.hasNextLine()){
                    message=scanner.nextLine();
                    broadcast(host+":"+message);
                }
            }catch(IOException e){
                e.printStackTrace();
            }finally {
                if(pw!=null){
                    synchronized (Server.this){
                        allOut.remove(pw);
                    }
                }
                try{
                    socket.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
                broadcast(host+"退出了聊天室！");
            }
        }
    }

}

